package sg.edu.nus.iss.billing.gui;

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;

import sg.edu.nus.iss.billing.controller.CustomerComplaintController;
import sg.edu.nus.iss.billing.controller.CustomerController;
import sg.edu.nus.iss.billing.entity.ComplaintStatus;
import sg.edu.nus.iss.billing.entity.Customer;
import sg.edu.nus.iss.billing.entity.CustomerComplaint;
import sg.edu.nus.iss.billing.entity.RecordState;
import sg.edu.nus.iss.billing.exception.ControllerException;
import sg.edu.nus.iss.billing.exception.ValidationException;
import sg.edu.nus.iss.billing.gui.component.ErrorDialog;
import sg.edu.nus.iss.billing.gui.component.ValidateJTextField;
import sg.edu.nus.iss.billing.localization.MessageKeyManager;
import sg.edu.nus.iss.billing.privilege.User;
import sg.edu.nus.iss.billing.util.UniqueKeyGenerator;
import sg.edu.nus.iss.billing.validation.ValidationRule;

public class LogComplaintPanel extends DefaultFunctionPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1257462897091593886L;
	private JLabel complaintKey;
	private ValidateJTextField nricTxt;
	private ValidateJTextField assignedToTxt;
	private ValidateJTextField reporterTxt;
	private JTextArea descriptionTxt;
	private CustomerComplaintController customerComplaintController;
	private JComboBox categoryCombo;
	private JComboBox severityCombo;
	private JPanel bottomPanel;
	
	private void clearAllFields() {
	  this.complaintKey.setText(UniqueKeyGenerator.createUniqueComplaintNo());
		this.nricTxt.setText("");
		this.assignedToTxt.setText("");
		this.descriptionTxt.setText("");
		this.categoryCombo.setSelectedIndex(0);
		this.severityCombo.setSelectedIndex(0);
		
		Customer customer = SessionContext.getCustomer();
		if ((customer != null) && (customer.getActive() == RecordState.ACTIVE)){
		  this.nricTxt.setText(SessionContext.getCustomer().getNRIC().toUpperCase());
		}
	}

	void saveButtonPressed() {	
		try {
			CustomerComplaint complaint = new CustomerComplaint();
	    CustomerController customerController = new CustomerController();
			Customer customer = customerController.getCustomerByNRIC(this.nricTxt.getValidatedText());
	    if (customer != null) {
	      if (customer.getActive() == RecordState.ACTIVE) {
    			complaint.setNRIC(this.nricTxt.getValidatedText());
    			complaint.setComplaints(this.descriptionTxt.getText());
    			complaint.setRemarks("");
    			complaint.setReportedDate(new Date());
    			complaint.setStatus(ComplaintStatus.PENDING);
    			complaint.setActive(RecordState.ACTIVE);
    			complaint.setComplaintRefKey(this.complaintKey.getText());
    			complaint.setAssignedTo(this.assignedToTxt.getValidatedText());
    			complaint.setReporter(this.reporterTxt.getText());
    			complaint.setCategory((String)this.categoryCombo.getModel().getSelectedItem());
    			complaint.setSeverity((String)this.severityCombo.getModel().getSelectedItem());
    			this.customerComplaintController.addCustomerComplaint(complaint);
    			JOptionPane.showMessageDialog(null, "New complaint has been created", "Add Complaint", JOptionPane.INFORMATION_MESSAGE);
    			clearAllFields();
	      } else {
          JOptionPane.showMessageDialog(null, "Customer has been DELETED!", "Add Complaint", JOptionPane.INFORMATION_MESSAGE);
	      }
	    }
		} catch (ValidationException ve) {
      ErrorDialog.showValidationErrorMessageDialog(ve);
    } catch (ControllerException ce) {
			ErrorDialog.showControllerErrorMessageDialog(ce);
		} catch (Exception ex) {
			ErrorDialog.showUnhandledErrorMessageDialog(ex);
		}
	}

	void resetButtonPressed() {				
		clearAllFields();
	}
	
	void cancelButtonPressed() {				
		clearAllFields();
	}

	/**
	 * Create the panel.
	 */
	public LogComplaintPanel() {
		super();
		this.customerComplaintController = new CustomerComplaintController();
		super.init(null);
	}

	@Override
	public JPanel createTopPanel() {
		return null;
	}

	@Override
	public JPanel createBottomPanel() {
		this.bottomPanel = new JPanel(new BorderLayout());
		this.bottomPanel.setBorder(new TitledBorder(null, MessageKeyManager
				.getMessage("label.enterComplaintDetails"), TitledBorder.LEADING,
				TitledBorder.TOP, null, null));

		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[]{0, 0, 0};
		gridBagLayout.rowHeights = new int[]{0, 0};
		gridBagLayout.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE};
		gridBagLayout.rowWeights = new double[]{0.0, Double.MIN_VALUE};

		JPanel contentPanel = new JPanel(gridBagLayout);
		this.bottomPanel.add(contentPanel, BorderLayout.NORTH);

		this.categoryCombo = new JComboBox();
		this.categoryCombo.setModel(new DefaultComboBoxModel(new String[] {
				MessageKeyManager.getMessage("combo.complaintType1"), 
				MessageKeyManager.getMessage("combo.complaintType2"), 
				MessageKeyManager.getMessage("combo.complaintType3"), 
				MessageKeyManager.getMessage("combo.complaintType4"), 
				MessageKeyManager.getMessage("combo.complaintType5"), 
				MessageKeyManager.getMessage("combo.complaintType6")}));

		this.severityCombo = new JComboBox();
		this.severityCombo.setModel(new DefaultComboBoxModel(new String[] {
				MessageKeyManager.getMessage("combo.severity.high"), 
				MessageKeyManager.getMessage("combo.severity.moderate"), 
				MessageKeyManager.getMessage("combo.severity.low")}));

		this.descriptionTxt = new JTextArea(10, 0);
		this.descriptionTxt.setEditable(true);
		this.descriptionTxt.setLineWrap(true);
	  JScrollPane scrollPane = new JScrollPane(this.descriptionTxt);

		this.complaintKey = new JLabel(UniqueKeyGenerator.createUniqueComplaintNo());
		this.nricTxt = new ValidateJTextField(MessageKeyManager.getMessage("label.NRIC/FIN"), ValidationRule.NOT_NULL, ValidationRule.NRIC);
		this.reporterTxt = new ValidateJTextField(MessageKeyManager.getMessage("label.reporter"), ValidationRule.NOT_NULL);
		this.assignedToTxt = new ValidateJTextField(MessageKeyManager.getMessage("label.assignedTo"), ValidationRule.NOT_NULL);

		String[] labels = new String[] {"label.status", "label.complaintID", "label.NRIC/FIN", "label.category",
				"label.severity", "label.description", "label.reporter", "label.assignedTo"};
		for (int i = 0; i < labels.length; i++) {
			GridBagHelper.addLabel(contentPanel, MessageKeyManager.getMessage(labels[i]), 
					SwingConstants.RIGHT, 0, i, GridBagConstraints.WEST, 0, GridBagHelper.INSETS_LARGE);
		}
		GridBagHelper.addLabel(contentPanel, MessageKeyManager.getMessage("label.pending"), 
				SwingConstants.LEFT, 1, 0, GridBagConstraints.WEST, 0, GridBagHelper.INSETS_LARGE);
		int x = 1;
		GridBagHelper.addComponent(contentPanel, this.complaintKey, 1, x++, 0, GridBagHelper.INSETS_LARGE);
		GridBagHelper.addComponent(contentPanel, this.nricTxt, 1, x++, 0, GridBagHelper.INSETS_LARGE);
		GridBagHelper.addComponent(contentPanel, this.categoryCombo, 1, x++, 0, GridBagHelper.INSETS_LARGE);
		GridBagHelper.addComponent(contentPanel, this.severityCombo, 1, x++, 0, GridBagHelper.INSETS_LARGE);
		GridBagHelper.addComponent(contentPanel, scrollPane, 1, x++, 0, GridBagHelper.INSETS_LARGE);
		GridBagHelper.addComponent(contentPanel, this.reporterTxt, 1, x++, 0, GridBagHelper.INSETS_LARGE);
		GridBagHelper.addComponent(contentPanel, this.assignedToTxt, 1, x++, 0, GridBagHelper.INSETS_LARGE);

		Customer customer = SessionContext.getCustomer();
    if ((customer != null) && (customer.getActive() == RecordState.ACTIVE)){
			this.nricTxt.setText(customer.getNRIC().toUpperCase());
		}
		User user = SessionContext.getUser();
		if (user != null) {
			this.reporterTxt.setText(user.getUsername());
		}
		this.reporterTxt.setEditable(false);
		return this.bottomPanel;
	}

	@Override
	public JPanel createActionButtonsPanel() {
		JPanel buttonPanel = new JPanel(new BorderLayout());
		
		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[]{0, 100, 10, 100, 0, 0};
		gridBagLayout.rowHeights = new int[]{24, 0};
		gridBagLayout.columnWeights = new double[]{1.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
		gridBagLayout.rowWeights = new double[]{0.0, Double.MIN_VALUE};

		JPanel contentPanel = new JPanel(gridBagLayout);
		buttonPanel.add(contentPanel, BorderLayout.NORTH);

		JButton btnNewButton = new JButton(MessageKeyManager.getMessage("button.log"));
		btnNewButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				saveButtonPressed();
			}
		});

		JButton btnReset = new JButton(MessageKeyManager.getMessage("button.reset"));
		btnReset.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				resetButtonPressed();
			}
		});

		GridBagHelper.addComponent(contentPanel, btnNewButton, 1, 0, 0, GridBagHelper.INSETS_LARGE);
		GridBagHelper.addComponent(contentPanel, btnReset, 3, 0, 0, GridBagHelper.INSETS_LARGE);

		return buttonPanel;
	}
}